//
//  LYChatViewController+TestData.swift
//  WeChat
//
//  Created by mac on 2018/9/5.
//  Copyright © 2018年 RRC. All rights reserved.
//

import Foundation
import SwiftyJSON

//MARK: - @extension LYChatViewController
// 聊天测试数据，仅仅是测试
extension LYChatViewController {
    //第一次请求的数据
    func firstFetchMessageList() {
        guard let list = self.fetchData() else {return}
        self.itemDataSouce.insert(contentsOf: list, at: 0)
        self.listTableView.reloadData()
    }
    
    //获取聊天列表数据
    func fetchData() -> [ChatModel]? {
        guard let JSONData = Data.ts_dataFromJSONFile("chat") else {
            return nil
        }
        
        var list = [ChatModel]()
        do {
            let jsonObj = try JSON(data: JSONData)
            var temp:ChatModel?
            for dict in jsonObj["data"].array! {
                let model = ChatModel().mapping(map: dict)
                if temp == nil || model.isLateForTwoMinutes(temp!){
                    guard let timestamp = model.timestamp else{
                        continue
                    }
                    list.insert(ChatModel(timestamp: timestamp), at: list.count)
                }
                list.insert(model, at: list.count)
                temp = model
            }
        } catch  {
            print("Error \(error)")
        }
        
        return list
    }
    
    //下拉刷新加载数据
    func updateTableWithNewCount(_ count:Int){
        var contentOffset = self.listTableView.contentOffset
        
        UIView.setAnimationsEnabled(false)
        self.listTableView.beginUpdates()
        
        var heightForNewRows: CGFloat = 0
        var indexPaths = [IndexPath]()
        for i in 0 ..< count {
            let indexPath = IndexPath(row: i, section: 0)
            indexPaths.append(indexPath)
            
//            heightForNewRows += self.tableView(self.listTableView, heightForRowAt: indexPath)
        }
        contentOffset.y += heightForNewRows
        
        self.listTableView.insertRows(at: indexPaths, with: UITableViewRowAnimation.none)
        self.listTableView.endUpdates()
        UIView.setAnimationsEnabled(true)
        self.listTableView.setContentOffset(contentOffset, animated: false)
    }
    
}
